package com.gxc.mq.provider;

import com.gxc.entity.User;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author GongXincheng
 * @since 2019-09-03 10:35
 */
@Component
public class TestQueueProvider {

    @Value("${gxc.queue.name.test-queue}")
    public String testQueue;

    @Resource
    private AmqpTemplate amqpTemplate;

    /**
     * 传递普通字符串
     */
    public void testQueueProvider(String message) {
        MessageProperties properties = new MessageProperties();
        properties.setHeader("key", "value");
        Message messages = new Message(message.getBytes(StandardCharsets.UTF_8), properties);
        amqpTemplate.send(testQueue, messages);
    }

    /**
     * 发送对象（将对象转为字节数组）.
     */
    public void testQueueProvider2(User user) throws IOException {
        // 将对象转为字节数组
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(user);
        byte[] bytes = bo.toByteArray();

        Message messages = new Message(bytes, new MessageProperties());
        amqpTemplate.send(testQueue, messages);
    }

    /**
     * 发送对象.
     */
    public void testQueueProvider3(User user) throws IOException {
        amqpTemplate.convertAndSend(testQueue, user);
    }

}
